package com.chipcoo;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.SubjectThreadState;
import org.apache.shiro.util.ThreadState;
import org.mockito.Mockito;

/**
 * Created by Administrator on 2016/5/8.
 */
public class ShiroTestHelper {
    private static ThreadState threadState;

    private ShiroTestHelper() {}

    /**
     * 綁定Subject到當前線程.
     */
    public static void bindSubject(Subject subject) {
        clearSubject();
        if(null==subject){
            subject = Mockito.mock(Subject.class);
        }
        threadState = new SubjectThreadState(subject);
        threadState.bind();
    }

    /**
     * 用Mockito快速創建一個已認證的用户.
     */
    public static void mockSubject(String principal) {
        Subject subject = Mockito.mock(Subject.class);
        Mockito.when(subject.isAuthenticated()).thenReturn(true);
        Mockito.when(subject.getPrincipal()).thenReturn(principal);

        bindSubject(subject);
    }

    /**
     * 清除當前線程中的Subject.
     */
    public static void clearSubject() {
        if (threadState != null) {
            threadState.clear();
            threadState = null;
        }
    }
}
